package com.aboo.frame.config.zookeeper;

import com.aboo.frame.util.ZkClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ZkConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${zookeeper.serverCluster}")
    private String zkServerCluster;
    @Value("${zookeeper.timeout}")
    private String zkTimeout;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 避免初始化两次的现象发生
        if (event.getApplicationContext().getParent() == null) {
            try {
                log.info("开始加载zookeeper，zkServerCluster:{}，zkTimeout:{}", zkServerCluster, zkTimeout);

                ZkClient.setZkServerCluster(zkServerCluster);
                ZkClient.setZkTimeout(Integer.parseInt(zkTimeout));
                ZkClient.connect();

                log.info("加载zookeeper完成");
            } catch (Exception e) {
                log.error("初始化zookeeper出错", e);
            }
        }
    }

}
